package org.infodavid.common.persistence.impl;

import java.io.Serializable;
import java.util.Collection;

import org.infodavid.common.persistence.IDataObject;
import org.infodavid.common.persistence.IDataService;
import org.infodavid.common.persistence.IPersistentData;

/**
 * The Class DataServiceHelper.
 * @param <T> the type of the data used when returning list items
 * @param <K> the type of the key of the data
 */
public class DataServiceHelper<T extends IPersistentData<K>,K extends Serializable> {

  /** The entity class. */
  private final Class<? extends T> entityClass;

  /** The service. */
  private final IDataService<T,K> service;

  /**
   * The Constructor.
   * @param arg0 the service
   */
  public DataServiceHelper(final IDataService<T,K> arg0) {
    if (arg0 == null) {
      throw new IllegalArgumentException("service");
    }

    service = arg0;
    entityClass = service.getEntityClass();
  }

  /**
   * Gets the entity class.
   * @return the entity class
   */
  public Class<? extends T> getEntityClass() {
    return entityClass;
  }

  /**
   * Gets the service.
   * @return the service
   */
  public IDataService<T,K> getService() {
    return service;
  }

  /**
   * Validate.
   * @param entities the entities
   */
  public void validate(final Collection<? extends T> entities) {
    if (entities == null) {
      throw new IllegalArgumentException("entities");
    }
  }

  /**
   * Validate.
   * @param key the key
   */
  public void validate(final K key) {
    if (key == null) {
      throw new IllegalArgumentException(IDataObject.KEY);
    }

    if (key instanceof Number && ((Number)key).longValue() <= 0) {
      throw new IllegalArgumentException(IDataObject.KEY + ':' + key);
    }
  }

  /**
   * Validate.
   * @param keys the keys
   */
  public void validate(@SuppressWarnings("unchecked")
  final K... keys) {
    if (keys == null || keys.length == 0) {
      throw new IllegalArgumentException("keys");
    }

    for (final K key : keys) {
      validate(key);
    }
  }

  /**
   * Validate.
   * @param entity the entity
   */
  public void validate(final T entity) {
    if (entity == null) {
      throw new IllegalArgumentException("entity");
    }
  }
}
